package com.andova.component.config;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;

import com.andova.component.AndovaComponentManager;

import java.lang.ref.WeakReference;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

/**
 * Created by Administrator on 2018-08-21.
 *
 * @author kzaxil
 * @since 0.0.2
 */
public class ConfigActivity extends AppCompatActivity {
    private ConfigAdapter mAdapter;

    static RefreshHandler sHandler;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.ac_component_config);

        sHandler = new RefreshHandler(this);

        mAdapter = new ConfigAdapter();

        RecyclerView rv = findViewById(R.id.rv_list);
        rv.setAdapter(mAdapter);
        rv.setLayoutManager(new LinearLayoutManager(this));
        rv.addItemDecoration(new BottomLineDecoration());

        refresh();
    }

    private void refresh() {
        AndovaConfigComponent acc = AndovaComponentManager.getInstance().configComponent();
        if (acc == null) return;
        List<String> nodes = acc.getConfigNode();
        if (nodes == null) return;
        mAdapter.clear();
        for (String node : nodes) {
            Set<String> altStringSet = acc.getAlternativeOfNode(node);
            Set<Value> altValueSet = null;
            if (altStringSet != null) {
                altValueSet = new HashSet<>(altStringSet.size());
                for (String key : altStringSet) {
                    altValueSet.add(new Value(key));
                }
            }
            mAdapter.add(new ConfigBean(node, acc.getValueOfNode(node), altValueSet));
        }
        mAdapter.notifyDataSetChanged();
    }

    static class RefreshHandler extends Handler {
        WeakReference<ConfigActivity> mWeakRef;

        RefreshHandler(ConfigActivity activity) {
            mWeakRef = new WeakReference<>(activity);
        }

        @Override
        public void handleMessage(Message msg) {
            final ConfigActivity activity = mWeakRef.get();
            if (activity == null) return;
            activity.refresh();
        }
    }
}
